$(function() {

  /**
  * Certificate
  * Module Export
  * Main certificate module
  */
  window.Certificate = (function () {
    var cert = {},
        default_info = {
          logo_file: "corpedia-logo.png", // DO NOT localize
          company: "Company", // Title of the comapny
          course_name: "Test Course Name", // Title of the course
          name: "This Student", // Name for student if none is provided
          instructions_string: "Please print and sign for your records.", // Instructions
          signature_string: "Sign", // Sign (signature)
          date_string: "Date", // Date
          print_button_value: "Print", // Print button display text
          print_string: "For best results, set printer to landscape orientation.", // Landscape
          error_text: "There was an error determining the user name for this session."
        },
        course_info,
        course_templates,
        student_name,
        $ = jQuery,
        debug_mode;
    
    /**
     * Utility function to get human-readable date.
     * @private
     * @returns Human-readable date
     * @type String
     */
    function getDate() {
      var monthArr = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      currentTime = new Date(),
      day = currentTime.getDate(),
      month = monthArr[currentTime.getMonth()],
      year = currentTime.getFullYear();

      return (month + " " + day + ", " + year);
    }
    
    /**
     * This function renders an error message on screen.
     * @private
     */
    function renderError(){
      $('#signature').hide();
      $('#title').html($.mustache("<p>{{error_text}}</p><p>Please re-open the certificate from the course window.</p>", default_info));
    }

    function renderAll(course_info){
      var m = $.mustache;

      $('#logo').html(m(course_templates.certificate_logo, course_info));
      $('#title').html(m(course_templates.certificate_title, course_info));
      $('#message').html(m(course_templates.certificate_certification, course_info));
      $('#instructions').html(m(course_templates.certificate_instructions, course_info));
      $('#signature-prompt').html(m(course_templates.certificate_signature_prompt, course_info));
      $('#certificate-date').html(m(course_templates.certificate_date, course_info));
      $('#date-prompt').html(m(course_templates.certificate_date_prompt, course_info));
      $('#print-panel').html(m(course_templates.print_description, course_info));
    }

    function normalizeStudentName(name){
      var split_name = name.split(',');

      if(split_name.length > 1){
        name = split_name[1] + " " + split_name[0];
      }

      return name;
    }
    
    function buildCourseInfo(course_info){
      var return_info = {}, i;

      for (i in default_info){
        if(!return_info.hasOwnProperty(i)){
          return_info[i] = course_info[i] || default_info[i];
        }
      }

      return_info.certificate_logo_location = return_info.logo_file;
      return_info.certificate_title = return_info.company + " " + return_info.course_name;
      return_info.certificate_course_name = return_info.course_name;
      return_info.certificate_name = normalizeStudentName(student_name);
      return_info.certificate_instructions = return_info.instructions_string;
      return_info.certificate_signature_prompt = return_info.signature_string;
      return_info.certificate_date_prompt = return_info.date_string;
      return_info.certificate_date = getDate();
      return_info.print_button_name = return_info.print_button_value;
      return_info.print_description = return_info.print_string;
      
      return return_info;
    }

    function userCookieAvailable(){
      
      try {
        if(window.opener.course !== undefined){
          var tracker = window.opener.course.tracker;
          student_name = tracker.get('cpda_student_name');
        } else if (window.opener.document.getElementById('movie') !== undefined) {
          student_name = window.opener.document.getElementById('movie').GetVariable('AICC_student_name'); 
        }
      } catch (e) {
        student_name = 'error';
      }
      
      if (debug_mode){
        student_name = 'Blars Tacoman';
      }
      
      return student_name !== 'error';
    }

    function init_() {
      debug_mode = cert.debug_mode = urlParams.debug === 'true'? true : false;
      
      if(userCookieAvailable()){
        course_info = cert.course_info = buildCourseInfo(window.course_info);
        course_templates = cert.course_templates = window.course_templates;
        renderAll(course_info);
      } else {
        renderError();
      }
    }

    cert.name = "Certificate";
    cert.version = "1.0_2012-04-12";

    cert.init = function() {
      init_();
    };

    return cert;
  
  }());

  /**
   * @constructor
   */
  Certificate.init();

});

var urlParams = {};

/**
 * This method creates an object of name-value pairs based on the contents of the querystring.
 * @returns An object containing the querystring converted to a hash.
 * @type Object
 */
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q)){
      urlParams[d(e[1])] = d(e[2]);
    }
}());
